package org.msfj.toilets.socket;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.msfj.common.context.SpringContextHelper;
import org.msfj.toilets.config.ToiletConfig;
import org.msfj.toilets.data.service.HumitureInfoService;
import org.msfj.toilets.data.service.PositionInfoService;
import org.msfj.toilets.model.HumitureInfo;
import org.msfj.toilets.model.PositionInfo;
import org.msfj.toilets.util.ByteUtil;
import org.msfj.toilets.vo.DataResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.tio.core.Node;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @User: Administrator
 * @Date: 2018/10/4 0004
 */
public class DataHandler {
    static Logger logger = LoggerFactory.getLogger(DataHandler.class);

    public static void handler(byte[] bytes, int size, Node node, String type, ToiletConfig toiletConfig) {
        long l = System.currentTimeMillis();
        if (size != 0) {
            logger.debug("接收到的{}消息为：{}", type, ByteUtil.bytesToHex(bytes, 0, size));
            String messageType = ByteUtil.getMessageType(bytes);
            logger.debug("消息类型为：{}", messageType);
            if ("65".equals(messageType.trim())) {
                DataResult dataResult = new DataResult();
                logger.debug("当前客户端的IP和端口为：{},", node.toString());
                logger.debug("接收到的64进制数据为：{}", ByteUtil.bytesToHex(bytes, 0, size));
                logger.debug("接收到的数据总长度为：{}", ByteUtil.getTotalSize(bytes));
                logger.debug("接收到的设备id为：{}", ByteUtil.getId(bytes));
                logger.debug("接收到的指令总长度为：{}", ByteUtil.getOrderSize(bytes));
                if (ByteUtil.getOrderSize(bytes) == 20) {
                    dataResult.setType(2);
                    String temperature = ByteUtil.getTemperature(bytes);
                    String humidity = ByteUtil.getHumidity(bytes);
                    dataResult.setTemperature(temperature);
                    dataResult.setHumidity(humidity);
                    logger.debug("温度为：{}，湿度为：{}", temperature, humidity);
                }
                if (ByteUtil.getOrderSize(bytes) == 13) {
                    dataResult.setType(3);
                    Map<String, Integer> womenInfo = new HashMap<>();
                    Map<String, Integer> menInfo = new HashMap<>();
                    Map<String, Integer> otherInfo = new HashMap<>();
                    String[] men = new String[10];
                    String[] women = new String[10];
                    String[] other = new String[10];
                    if (StrUtil.isNotBlank(toiletConfig.getMen())) {
                        men = toiletConfig.getMen().split(",");
                    }
                    if (StrUtil.isNotBlank(toiletConfig.getWomen())) {
                        women = toiletConfig.getWomen().split(",");
                    }
                    if (StrUtil.isNotBlank(toiletConfig.getOther())) {
                        other = toiletConfig.getOther().split(",");
                    }
                    if (toiletConfig.getCount() > 0) {
                        byte[] ioInfo = ByteUtil.getIoInfo(bytes, 22, 23);
                        menInfo = setInfo(menInfo, men, ioInfo, "A");
                        womenInfo = setInfo(womenInfo, women, ioInfo, "A");
                        otherInfo = setInfo(otherInfo, other, ioInfo, "A");
                    }
                    if(toiletConfig.getCount() > 1){
                        byte[] ioInfo = ByteUtil.getIoInfo(bytes, 24, 25);
                        menInfo = setInfo(menInfo, men, ioInfo, "B");
                        womenInfo = setInfo(womenInfo, women, ioInfo, "B");
                        otherInfo = setInfo(otherInfo, other, ioInfo, "B");
                    }
                    if (toiletConfig.getCount() > 2) {
                        byte[] ioInfo = ByteUtil.getIoInfo(bytes, 26, 27);
                        menInfo = setInfo(menInfo, men, ioInfo, "C");
                        womenInfo = setInfo(womenInfo, women, ioInfo, "C");
                        otherInfo = setInfo(otherInfo, other, ioInfo, "C");
                    }
                    if (toiletConfig.getCount() > 3) {
                        byte[] ioInfo = ByteUtil.getIoInfo(bytes, 28, 29);
                        menInfo = setInfo(menInfo, men, ioInfo, "D");
                        womenInfo = setInfo(womenInfo, women, ioInfo, "D");
                        otherInfo = setInfo(otherInfo, other, ioInfo, "D");
                    } else {

                    }
                    if (MapUtil.isNotEmpty(menInfo)) {
                        dataResult.setMenInfo(menInfo);
                    }
                    if (MapUtil.isNotEmpty(womenInfo)) {
                        dataResult.setWomenInfo(womenInfo);
                    }
                    if (MapUtil.isNotEmpty(otherInfo)) {
                        dataResult.setOtherInfo(otherInfo);
                    }
                    saveValue(dataResult);
                }
                saveValue(dataResult);
                SimpMessagingTemplate messagingTemplate = SpringContextHelper.getBean(SimpMessagingTemplate.class);
                messagingTemplate.convertAndSend("/data", JSONUtil.toJsonStr(dataResult));
            }
        }
    }

    private static void saveValue(DataResult dataResult) {
        if (ObjectUtil.isNotNull(dataResult)) {
            if (StrUtil.isNotBlank(dataResult.getTemperature()) || StrUtil.isNotBlank(dataResult.getHumidity())) {
                HumitureInfoService bean = SpringContextHelper.getBean(HumitureInfoService.class);
                HumitureInfo humitureInfo = new HumitureInfo();
                humitureInfo.setCreateBy("1");
                humitureInfo.setUpdateBy("1");
                humitureInfo.setJson("{\"temperature\":\"" + dataResult.getTemperature() + "\",\"humidity\":\"" + dataResult.getHumidity() + "\"}");
                bean.saveOrEdit(humitureInfo);
            } else {
                PositionInfoService bean = SpringContextHelper.getBean(PositionInfoService.class);
                PositionInfo positionInfo = new PositionInfo();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("men", dataResult.getMenInfo());
                jsonObject.put("women", dataResult.getWomenInfo());
                jsonObject.put("other", dataResult.getOtherInfo());
                positionInfo.setCreateBy("1");
                positionInfo.setUpdateBy("1");
                positionInfo.setJson(jsonObject.toString());
                bean.saveOrEdit(positionInfo);
            }
        }
    }

    private static Map<String, Integer> setInfo(Map<String, Integer> map, String[] strs, byte[] bytes, String position) {
        if (ArrayUtil.isNotEmpty(strs)) {
            for (int i = 0; i < bytes.length; i++) {
                for (String woman : strs) {
                    String s = new StringBuffer(position).append(i).toString();
                    if (s.equalsIgnoreCase(woman)) {
                        map.put(s, (int) bytes[i]);
                    }
                }
            }

        }
        return map;
    }
}
